<template>
  <el-tree
    ref="treeRef"
    :data="props.data"
    show-checkbox
    node-key="id"
    :props="{
      children: 'children',
      label: 'name'
    }"
    :default-expanded-keys="props.defaultExpandedKeys || []"
    :default-expand-all="false"
    highlight-current
    check-on-click-node
    :expand-on-click-node="false"
    @check="handleChange"
  />
</template>

<script lang="ts" setup>
import { ElTree } from "element-plus";
import { useComponentRef } from "@/hooks";

const props = defineProps<{
  data: Recordable[];
  checkList: Recordable[];
  defaultExpandedKeys?: string[];
}>();

const emit = defineEmits(["checkChange"]);

// const treeRef = ref<InstanceType<typeof ElTree>>();
const treeRef = useComponentRef(ElTree);

const handleChange = (_, node) => {
  const checkedNodes = node.checkedNodes.filter((item) => item.type === 'user' || item.type === '3');
  emit("checkChange", checkedNodes);
};

const setCheckedKeys = (value: Recordable[]) => {
  treeRef.value!.setCheckedKeys(value.map((item) => item.id as number));
};

defineExpose({
  setCheckedKeys
});
</script>
